<?php
###
#  Baing PHP 框架 1.0.0
#  http://baing.co/
#
#  Copyright: 白晓阳
#  License: CC BY-NC-SA 4.0
#  https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh
###

namespace bai\feature;


trait Files
{
    final public static function mergeConfig(array $config, string|array $list): array
    {
        if (is_string($list)) {
            $list = is_file($list) ? require $list : [];
        }
        if (!is_array($list)) return $config;

        foreach ($list as $key => $value) {
            if (!isset($config[$key]) || !is_array($config[$key]) || !is_array($value)) {
                $config[$key] = $value;
                continue;
            }
            if (array_key_first($config[$key]) === 0 && array_key_first($value) === 0) {
                $config[$key] = array_merge($config[$key], $value);
                continue;
            }
            $config[$key] = self::mergeConfig($config[$key], $value);
        }
        return $config;
    }

    final public static function scanFiles(string $root, callable $action)
    {
        static $exclude = ['.', '..'];

        $result = [];
        if (!is_dir($root) || !($files = scandir($root))) {
            return $result;
        }

        foreach ($files as $file) {
            if (in_array($file, $exclude)) continue;
            $path = "$root/$file";
            if (is_dir($path)) {
                $result = array_merge_recursive($result, self::scanFiles($path, $action));
                continue;
            }
            $action($file, $path, $result);
        }
        return $result;
    }

    final public static function toPhp(array $content): string
    {
        return '<?php return ' . var_export($content, true) . ';';
    }
}